<template>
  <div ref="videoRef" class="video"></div>
</template>

<script setup>
import DPlayer from 'dplayer'
import { ref, reactive, onBeforeUnmount, onMounted, defineEmits, defineExpose } from 'vue'

const videoRef = ref()
const state = reactive({
  instance: null
})

const props = defineProps({
  // 是否自动播放
  autoplay: {
    type: Boolean,
    default: true
  },
  // 主题色
  theme: {
    type: String,
    default: '#0093ff'
  },
  // 视频是否循环播放
  loop: {
    type: Boolean,
    default: false
  },
  // 语言(可选值: 'en', 'zh-cn', 'zh-tw')
  lang: {
    type: String,
    default: 'en'
  },
  // 是否开启截图(如果开启，视频和视频封面需要允许跨域)
  screenshot: {
    type: Boolean,
    default: false
  },
  // 是否开启热键
  hotkey: {
    type: Boolean,
    default: true
  },
  // 视频是否预加载(可选值: 'none', 'metadata', 'auto')
  preload: {
    type: String,
    default: 'auto'
  },
  // 默认音量
  volume: {
    type: Number,
    default: 0.7
  },
  // 可选的播放速率，可以设置成自定义的数组
  playbackSpeed: {
    type: Array,
    default: [1]
  },

  // 视频信息
  video: {
    type: Object,
    default: {}
  },
  // 外挂字幕
  subtitle: {
    type: Object,
    default: {}
  },
  // 显示弹幕
  danmaku: {
    type: Object,
    default: {}
  },
  // 自定义右键菜单
  contextmenu: {
    type: Array,
    default: []
  },
  // 自定义进度条提示点
  highlight: {
    type: Array,
    default: []
  },
  // 阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
  mutex: {
    type: Boolean,
    default: true
  },
  videoStatus: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['changeVideo', 'playVideo', 'stopVideo'])
const playVideo = () => {
  state.instance.video.play()
}
const stopVideo = () => {
  state.instance.video.pause()
}
const changeVideo = () => {
  emit('changeVideo')
}
const switchVideourl = (data) => {
  state.instance.switchVideo(data)
  state.instance.video.play()
}
defineExpose({ switchVideourl, playVideo, stopVideo })
onMounted(() => {
  let player = {
    container: videoRef.value,
    autoplay: true,
    theme: props.theme,
    loop: props.loop,
    lang: props.lang,
    screenshot: props.screenshot,
    hotkey: props.hotkey,
    preload: props.preload,
    volume: props.volume,
    playbackSpeed: props.playbackSpeed,
    video: props.video
    // contextmenu: props.contextmenu,
    // highlight: props.highlight,
    // mutex: props.mutex
  }
  if (props.subtitle.url) {
    player.subtitle = props.subtitle
  }
  state.instance = new DPlayer(player)

  state.instance.on('ended', function () {
    changeVideo()
  })

  state.instance.on('pause', function () {
    if (props.videoStatus) {
      state.instance.video.play()
    } else {
      state.instance.video.pause()
    }
  })
  state.instance.on('play', function () {
    if (props.videoStatus) {
      state.instance.video.play()
    } else {
      state.instance.video.pause()
    }
  })
})
// 销毁
onBeforeUnmount(() => {
  state.instance.destroy()
})
</script>

<style lang="scss" scoped>
.video {
  width: 100%;
  height: 100%;
}
</style>
